#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: get_requirements_id_by_tcase.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 获取测试用例关联的需求id
https://open.tapd.cn/document/api-doc/API%E6%96%87%E6%A1%A3/api_reference/tcase/get_story_by_tcase_id.html
"""


from comm.common_code import *
def get_requirements_id_by_tcase(tcase_ids, max_retries=5):
    """查询指定目录ID（精确匹配）,返回目录ID和目录名称
    :param parent_id: 父目录ID,=0时范围是“所有的，=xxxx则查询xxxx目录下的”
    :param dir_name: 目录名称
    :param max_retries: 最大重试次数（针对429限流）
    """
    excel_data = get_excel_data()
    url = f"https://api.tapd.cn/tcases/get_story_by_tcase_id?workspace_id={excel_data['项目ID']}&tcase_ids={tcase_ids}&access_token={excel_data['access_token']}"
    payload = {}
    
    retries = 0
    while retries <= max_retries:
        response_code, response = api_request(method='GET', url=url, headers={}, data=payload)
        
        if response_code == 429:  # 限流错误
            retries += 1
            if retries > max_retries:
                logger.error("达到最大重试次数，仍然被限流")
                return response_code, response
                
            # 计算等待时间（指数退避）
            wait_time = 2 ** retries
            logger.warning(f"遇到限流，等待{wait_time}秒后重试 ({retries}/{max_retries})")
            time.sleep(wait_time)
            continue
            
        logger.info(f"响应内容: {response}")
        logger.info(f'↑↑↑=================================================↑↑↑')
        return response_code, response

if __name__ == "__main__":
    # dir_get_id_and_name(parent_id='', dir_name='')
    get_requirements_id_by_tcase(tcase_ids='1166606973001110922')
